import matplotlib.pyplot as plt
import numpy as np
from matplotlib.font_manager import FontProperties

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei','DejaVu Sans']  
plt.rcParams['axes.unicode_minus'] = False  

def demonstrate_one_sided_continuity():
    """
    演示单侧连续性的概念和应用
    """
    # 创建图形和子图
    fig, axes = plt.subplots(1, 3, figsize=(15, 5))
    
    # 例4：f(x)在x=0处连续（左右都连续）
    x1_left = np.linspace(-2, 0, 100)
    x1_right = np.linspace(0, 2, 100)
    
    # f(x) = {x+1, x≤0; x²+1, x>0}
    y1_left = x1_left + 1
    y1_right = x1_right**2 + 1
    
    axes[0].plot(x1_left, y1_left, 'b-', linewidth=2, label='x≤0: f(x)=x+1')
    axes[0].plot(x1_right, y1_right, 'r-', linewidth=2, label='x>0: f(x)=x²+1')
    axes[0].plot(0, 1, 'ro', markersize=8, label='f(0)=1')
    axes[0].set_title('例4: f(x)在x=0处连续\n左右极限都等于f(0)=1')
    axes[0].set_xlabel('x')
    axes[0].set_ylabel('f(x)')
    axes[0].legend()
    axes[0].grid(True, alpha=0.3)
    
    # 例5：取整函数在整数点右连续但不左连续
    x_floor = np.linspace(-2, 2, 1000)
    y_floor = np.floor(x_floor)
    
    # 绘制取整函数
    for i in range(-2, 2):
        mask = (x_floor >= i) & (x_floor < i+1)
        axes[1].plot(x_floor[mask], y_floor[mask], 'g-', linewidth=2)
    
    # 标记在x=1处的单侧连续性
    axes[1].plot(1, 1, 'go', markersize=8, label='右连续点: f(1)=1')  # 右连续点
    axes[1].plot(1, 0, 'ro', markersize=8, fillstyle='none', label='左不连续点: lim(x→1-)=0')  # 左不连续点
    axes[1].set_title('例5: 取整函数y=[x]\n在整数点右连续但不左连续')
    axes[1].set_xlabel('x')
    axes[1].set_ylabel('[x]')
    axes[1].legend()
    axes[1].grid(True, alpha=0.3)
    
    # 例6：f(x)在x=0处连续
    x6_left = np.linspace(-1, -0.001, 100)
    x6_right = np.linspace(0.001, 1, 100)
    
    # f(x) = {ln(1-x)/x, x<0; x²-1, x≥0}
    y6_left = np.log(1 - x6_left) / x6_left
    y6_right = x6_right**2 - 1
    
    axes[2].plot(x6_left, y6_left, 'b-', linewidth=2, label='x<0: f(x)=ln(1-x)/x')
    axes[2].plot(x6_right, y6_right, 'r-', linewidth=2, label='x≥0: f(x)=x²-1')
    axes[2].plot(0, -1, 'ro', markersize=8, label='f(0)=-1')
    axes[2].set_title('例6: f(x)在x=0处连续')
    axes[2].set_xlabel('x')
    axes[2].set_ylabel('f(x)')
    axes[2].legend()
    axes[2].grid(True, alpha=0.3)
    
    plt.tight_layout()
    plt.show()

# 运行演示
demonstrate_one_sided_continuity()